from django.core.mail import send_mail
from django.conf import settings
from rest_framework import serializers
from users.models import User
from django_redis import get_redis_connection
import re
from rest_framework_jwt.settings import api_settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJS

from celery_tasks.send_emails.tasks import send_email


class UserSerialzier(serializers.ModelSerializer):
    # 显示指明模型类中没有的字段
    password2 = serializers.CharField(max_length=20, min_length=8, write_only=True)
    sms_code = serializers.CharField(max_length=6, min_length=6, write_only=True)
    allow = serializers.CharField(write_only=True)
    token = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ('username', 'mobile', 'password', 'password2', 'sms_code', 'allow', 'id', 'token')
        extra_kwargs = {
            'password': {
                'max_length': 20,
                'min_length': 8,
                'write_only': True
            },
            'username': {
                'max_length': 20,
                'min_length': 5,
            },
        }

    # 验证手机号格式
    def validate_mobile(self, value):

        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式不正确')

        return value

    # 验证选中状态
    def validate_allow(self, value):

        if value != 'true':
            raise serializers.ValidationError('协议未选中')

        return value

    def validate(self, attrs):

        # username是手机号格式
        if re.match(r'^1[3-9]\d{9}$', attrs['username']):
            # 验证手机号和用户名名是否一致
            if attrs['mobile'] != attrs['username']:
                raise serializers.ValidationError('手机号和用户名不一致')

        # 密码验证
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('密码不一致')

        # 短信验证
        # 1、建立redis连接
        conn = get_redis_connection('sms_code')
        # 2、获取真实的短信验证码
        real_sms_code = conn.get('sms_code_%s' % attrs['mobile'])
        # 3、判断是在有效期内
        if not real_sms_code:
            raise serializers.ValidationError('验证码失效')
        # 4、比对用户输入的和真实验证码
        if attrs['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('验证码错误')

        return attrs

    def create(self, validated_data):

        # 删除不需要的字段数据
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        # 保存用户对象
        user = User.objects.create_user(**validated_data)

        # User.objects.create_user(username=validated_data['username'])



        # 生成JWT token值
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 在user对象中添加token属性
        user.token = token

        return user


class UserDetailSerialzier(serializers.ModelSerializer):
    # 用户信息展示
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class UserEmailSerialzier(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('email',)

    def update(self, instance, validated_data):
        instance.email = validated_data['email']
        instance.save()
        # 加密用户数据生成token
        data = {'user_id': instance.id, 'email': validated_data['email']}
        tjs = TJS(settings.SECRET_KEY, 300)
        token = tjs.dumps(data).decode()
        to_email = validated_data['email']

        # # 将token拼接到验证链接中
        # verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token
        #
        # subject = "美多商城邮箱验证"
        # html_message = '<p>尊敬的用户您好！</p>' \
        #                '<p>感谢您使用美多商城。</p>' \
        #                '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
        #                '<p><a href="%s">%s<a></p>' % (to_email, verify_url, verify_url)
        # # 发送邮件

        # send_mail(subject,'',settings.EMAIL_FROM,[validated_data['email']],html_message=html_message)
        # 使用celery 发送邮件
        send_email.delay(token, to_email)

        return instance


# class PasswordChange(serializers.ModelSerializer):
#     password = serializers.CharField(write_only=True)
#     password2 = serializers.CharField(write_only=True)
#     old_password = serializers.CharField(write_only=True)
#
#     class Meta:
#         model = User
#         fields = ("old_password", "password", "password2",)
#
#     def validate_old_password(self, value):
#         print("验证密码")
#         user = self.context['request'].user
#         if not user.check_password(value):
#             raise serializers.ValidationError("密码错误")
#
#         print("验证密码成功")
#
#         return value
#
#     def validate(self, data):
#
#         if data['password'] != data['password2']:
#             raise serializers.ValidationError("两次新密码密码输入不一致")
#         return data
#
#     def update(self, instance, validated_data):
#         print(instance)
#         try:
#             instance.set_password(validated_data['password'])
#             instance.save()
#         except Exception as e:
#             print(e)
#             raise serializers.ValidationError("修改密码失败")
#
#         print(instance)
#         return instance
